package com.controller;

import com.entity.News;
import com.entity.Notification;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@WebServlet("/index")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<News> newsList = new ArrayList<>();
        List<Notification> notificationsList = new ArrayList<>();
        String sqlNews = "select * from news";
        String sqlNotis = "select * from notifications";
        try (Connection conn = DataSourceUtils.getConnection();
             PreparedStatement st = conn.prepareStatement(sqlNews)) {
            try(ResultSet rs = st.executeQuery(sqlNews)) {
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String newsType = rs.getString("type");
                    String title = rs.getString("title");
                    String content = rs.getString("content");
                    Date addTime = rs.getDate("addtime");
                    News news = new News(id, title, newsType, content, addTime);
                    newsList.add(news);
                }
                Collections.reverse(newsList);
            }
            try(ResultSet rs = st.executeQuery(sqlNotis)) {
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String title = rs.getString("title");
                    String content = rs.getString("content");
                    Date addTime = rs.getDate("add_time");
                    Notification notification = new Notification(id, title,  content, addTime);
                    notificationsList.add(notification);
                }
                Collections.reverse(notificationsList);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        req.setAttribute("news", newsList);
        req.setAttribute("notifications", notificationsList);
        req.getRequestDispatcher("/index.jsp").forward(req, resp);
    }
}
